﻿using Alipay.AopSdk.Core;
using Alipay.AopSdk.Core.Domain;
using Alipay.AopSdk.Core.Request;
using Alipay.AopSdk.Core.Response;
using Alipay.AopSdk.Core.Util;
//using ServiceStack.Configuration;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZhouYu.DreamTour.Model;
using ZhouYu.DreamTour.ViewModel.AlipayOrder;
using ZhouYu.DreamTour.Web.Models;

namespace ZhouYu.DreamTour.Web.Controllers
{
    public class Specialt_PayController : Controller
    {
        public ActionResult Specialt_AlipayIndex(string Order_No, string Order_ProInfo,string total, string Order_Content)
        {
            //获取订单编号
            ViewBag.Order_No = Order_No;
            //获取产品名称
            ViewBag.Order_ProInfo = Order_ProInfo;
            //获取商品总价
            ViewBag.total = total;
            //获取商品描述
            ViewBag.Order_Content = Order_Content;
            return View();
        }


        public ActionResult Specialt_Notice(OrderInfo order)
        {

            int userid = UserInfoContext.userInfoContext.UserInfo.User_Id != 0 ? UserInfoContext.userInfoContext.UserInfo.User_Id : 0;//没有读取到用户的id
            string UserID = userid.ToString();

            //开发者账号配置加载
            DefaultAopClient client = new DefaultAopClient(Config.gatewayUrl, Config.app_id, Config.private_key, "json", "1.0", Config.sign_type, Config.alipay_public_key, Config.charset, false);

            // 组装业务参数model
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.Body = order.Order_Content + "/" + UserID;// 商品描述
            model.Subject = order.Order_ProInfo; // 订单名称
            model.TotalAmount = order.Order_Money.ToString();// 付款金额
            model.OutTradeNo = order.Order_No; // 外部订单号，商户网站订单系统中唯一的订单号
            model.ProductCode = "FAST_INSTANT_TRADE_PAY";

            //model.PassbackParams = UserID;

            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            // 设置支付完成异步通知接收地址
            request.SetNotifyUrl("https://localhost:44336/PaymentRecord/AddPaymentRecord");//异步通知地址很重要，该异步页面主要用来支付成功后，进行相关的数据库操作

            // 设置支付完成同步回调地址
            request.SetReturnUrl("https://localhost:44336/Home/User_Order?Order_No=" + order.Order_No);//支付成功后返回的地址
            request.SetBizModel(model);
            
            AlipayTradePagePayResponse response = null;
            try
            {
                response = client.PageExecute(request, null, "post");
                //Response.Write(response.Body);  原本无隐藏的初始代码
                string newhtml = "<div style=\"display:none\">" + response.Body + "</div>";//加这段将表单进行隐藏提交
                Response.Write(newhtml);
            }
            catch (Exception exp)
            {
                throw exp;
            }
            return View();
        }

        public ActionResult Specialt_Notify()
        {
            Dictionary<string, string> sArray = GetRequestPost();

            if (sArray.Count != 0)
            {
                bool flag = AlipaySignature.RSACheckV1(sArray, Config.alipay_public_key, Config.charset, Config.sign_type, false);
                if (flag)
                {
                    //交易状态
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                    //如果有做过处理，不执行商户的业务程序

                    //注意：
                    //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    string trade_status = Request.Form["trade_status"];

                    if (trade_status == "TRADE_SUCCESS")// 判断支付状态_交易成功
                    {
                        #region 获取相应的订单信息
                        //商户订单号
                        string out_trade_no = Request.Form["out_trade_no"];
                        //支付宝交易号
                        string trade_no = Request.Form["trade_no"];
                        //支付金额
                        decimal total_amount = Convert.ToDecimal(Request.Form["total_amount"].ToString());//ConvertType(Decimal.Zero);
                                                                                                          //实收金额
                                                                                                          //decimal receipt_amount = Request.Form["receipt_amount"].ConvertType(Decimal.Zero);
                                                                                                          //卖家支付宝账号
                        string seller_id = Request.Form["seller_id"];

                        //商品描述
                        string bodys = Request.Form["body"];
                        //body 商品描述
                        string body = "";
                        //用户id
                        string userid = "";
                        if (!string.IsNullOrEmpty(bodys))
                        {
                            string[] piont = bodys.Split('/');
                            body = piont[0];
                            userid = piont[1];
                        }//我这里用了个小聪明，把一个重要的数据库判断字段（用户的ID字段）加在了商品描述里，然后用/把两个字段分割开获取
                         //交易创建时间
                        DateTime gmt_create = DateTime.Parse(Request.Form["gmt_create"]);
                        //交易付款时间
                        DateTime gmt_payment = DateTime.Parse(Request.Form["gmt_payment"]);
                        //获取用户的id
                        int UserID = 0;
                        UserID = Convert.ToInt32(userid);

                        #endregion

                        #region 估价单付款成功的操作
                        if (body == "估价单付款")
                        {
                            //在数据库中提交估价单的订单信息

                        }

                    }
                    #endregion

                    Response.Write("success");
                }

            }
            else
            {
                Response.Write("fail");
            }

            return View();
        }


        public Dictionary<string, string> GetRequestPost()
        {
            int i = 0;
            Dictionary<string, string> sArray = new Dictionary<string, string>();
            NameValueCollection coll;
            //coll = Request.Form;
            coll = Request.QueryString;
            String[] requestItem = coll.AllKeys;
            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], Request.Form[requestItem[i]]);
            }
            return sArray;

        }
    }
}